//: src/com/silvtar/util/Md5.java
/* 
 * Created by 朴晟宁 <piaosn@gmail.com> on 4/21/2013. 
 * Copyright (c) 2013 朴晟宁. All rights reserved.
 * 
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program;
 * 
 * *********************************************************************
 * 
 * Modify History:
 * Date        Version    Description
 * 4/23/2013   0.1        Create the class
 */

package com.silvtar.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.silvtar.io.StdOut;

/**
 * MD5类，负责计算MD5值
 * 
 * @author 朴晟宁/Silvtar
 * @author piaosn@gmail.com
 * @version 0.1
 */
public class Md5 {

    private static final String  Md5           = null;

    /**
     * 默认的密码字符串组合，用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
     */
    private static char          hexDigits[]   = { '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    private static MessageDigest messagedigest = null;
    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException nsaex) {
            StdOut.printErrLog(Md5, "初始化失败，MessageDigest不支持MD5Util。");
            nsaex.printStackTrace();
        }
    }

    
    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {

        char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>
                                              // 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同
        char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {

        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static String bufferToHex(byte bytes[]) {

        return bufferToHex(bytes, 0, bytes.length);
    }

    /**
     * 获得md5值
     * 
     * @param bytes
     *            要计算的字节数组
     * @return 16进制MD5值
     */
    public static String getMD5String(byte[] bytes) {

        messagedigest.update(bytes);
        return bufferToHex(messagedigest.digest());
    }

    /**
     * 获得文件的MD5值
     * 
     * @param file
     *            要计算的文件
     * @return 16进制MD5值
     * @throws IOException
     *             当读取文件出错，会抛出此异常。
     */
    public static String getFileMD5String(File file) throws IOException {

        InputStream iStream;

        iStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int numRead = 0;
        while ((numRead = iStream.read(buffer)) > 0) {
            messagedigest.update(buffer, 0, numRead);
        }
        iStream.close();
        return bufferToHex(messagedigest.digest());
    }

}
